package com.googlecode.maratische.google.gui;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.googlecode.maratische.google.MainController;
import com.googlecode.maratische.google.MainFrame;
import com.googlecode.maratische.google.model.Item;
import com.googlecode.maratische.google.model.Spam;

public class SpamForm extends JDialog {
	
	private static final long serialVersionUID = 3237971421654126882L;

	private JCheckBox checkBoxTitle = new JCheckBox("Title: ");
	private JComboBox boxTitleType = new JComboBox(Spam.spamTypes);
	private JTextField fieldTitle = new JTextField(30);
	private Spam spam = null;
	
	public SpamForm(MainFrame mainFrame) {
		super(mainFrame, true);
		setSize(600, 500);
		setTitle("Spam!");
		setLayout(new GridLayout(4, 1));
		
		
		JPanel panel1 = new JPanel();
		panel1.setLayout(new FlowLayout(FlowLayout.LEFT));
		panel1.add(checkBoxTitle);
		panel1.add(boxTitleType);
		panel1.add(fieldTitle);
		add(panel1);
		
		JPanel panel2 = new JPanel();
		add(panel2);
		
		JPanel panel3 = new JPanel();
		add(panel3);
		
		JPanel panel4 = new JPanel();
		panel4.setLayout(new FlowLayout(FlowLayout.CENTER));
		JButton btnOk = new JButton("Save");
		panel4.add(btnOk);
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				save();
			}
		});
		JButton btnCancel = new JButton("Cancel");
		panel4.add(btnCancel);
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				close();
			}
		});
		add(panel4);

		Item item = MainController.getMainController().getSelectedItem();
		if (item != null) {
			fieldTitle.setText(item.getTitle());
			checkBoxTitle.setSelected(true);
		}

	}

	private void save() {
		if (checkBoxTitle.isSelected()) {
			String title = fieldTitle.getText();
			if (title.trim().length()==0) {
				//ERROR TODO сделать обработку ошибки
				return;
			}
			spam = new Spam();
			spam.setCount(0);
			spam.setTitleType(boxTitleType.getSelectedIndex());
			spam.setTitle(title);
			spam.setDescriptionType(0);
			spam.setDescription("");
			spam.setDateStop(new Date());
		}
		close();
	}
	
	private void close() {
		this.dispose();
	}
	
	public Spam getSpam() {
		return this.spam;
	}

}
